package main

import (
	"biliClient/core"
	"biliClient/global"
	"biliClient/model"
	"biliClient/redis"
	"biliClient/utils"
	"context"
	"encoding/json"
	"fmt"
	"strings"
	"sync"
	"time"
)

// Handshake 保持心跳
func Handshake(wg *sync.WaitGroup) {
	defer wg.Done()
	i := 0
	for {
		i++
		redis.SetValue(global.MacID, i, 10)
		time.Sleep(time.Second * 6)
	}
}

// RunTask 开始执行
func RunTask(task model.Task) {
	var (
		wg       sync.WaitGroup
		errCh    = make(chan int)
		errCount int
		over     = make(chan struct{})
	)
	// 整体超时时间10秒
	timeout, cancelFunc := context.WithTimeout(context.Background(), time.Second*100)
	defer cancelFunc()
	urls := strings.Split(task.Durl, "----")
	result, _url := core.TestStream(urls)
	if result {
		for i := 0; i < task.Count; i++ {
			wg.Add(1)
			go core.FlvPullStream(_url, errCh, over, &wg)
			// 启动间隔100毫秒
			time.Sleep(time.Millisecond * 100)
		}
	}
	// 协程结束时要清理一些参数
	go func() {
		defer close(errCh)
		wg.Wait()
		global.Glock.Lock()
		global.TaskList = TaskDel(global.TaskList, task)
		global.Glock.Unlock()
		fmt.Println("我被执行了")
	}()

	// 处理各种Channel参数反馈
	for {
		select {
		case err := <-errCh:
			global.Log.Errorf("func:RunTask -> case <-errCh:%v   Room:%v\n", err, task.RoomID)
			errCount++
			if errCount > 10 {
				global.Log.Errorf("func:RunTask -> if errCount > 10:   Room:%v\n", task.RoomID)
				close(over)
				global.Glock.Lock()
				global.TaskList = TaskDel(global.TaskList, task)
				global.Glock.Unlock()
				return
			}
		case <-timeout.Done():
			close(over)
			global.Log.Debugf("func:RunTask -> case <-timeout.Done():   Room:%v\n", task.RoomID)
			return
		default:
			time.Sleep(time.Millisecond * 100)
		}
	}
}

//GetTaskList 获取任务列表
func GetTaskList(wg *sync.WaitGroup) {

	defer wg.Done()
	for {
		list := redis.GetLis(global.MacID)
		if list != nil {
			for _, s := range list {
				var task model.Task
				_ = json.Unmarshal([]byte(s), &task)
				if TaskExists(global.TaskList, task) {
					global.Glock.Lock()
					global.TaskList = append(global.TaskList, task)
					global.Glock.Unlock()
					global.Log.Debugf("func:GetTaskList -> if TaskExists(global.TaskList, task)   Room:%v	Count:%v\n", task.RoomID, task.Count)
					go RunTask(task)
				}
			}
		}
		time.Sleep(time.Second * 10)
	}
}

// TaskExists 检查成员是否存在
func TaskExists(list []model.Task, task model.Task) bool {
	for _, i := range list {
		if i.RoomID == task.RoomID {
			return false
		}
	}
	return true
}

// TaskDel 删除已完成的任务
func TaskDel(list []model.Task, task model.Task) []model.Task {
	for k, v := range list {
		if v.RoomID == task.RoomID {
			list = append(list[:k], list[k+1:]...)
			return list
		}
	}
	return nil
}

// Init 网卡名称
func Init(deviceName string) {
	global.MacID =core.CheckDeviceID(utils.GetMac(deviceName))
}
func main() {
	Init("ens192")
	global.Log.Debugf("device:%v",global.MacID)
	wg := sync.WaitGroup{}
	wg.Add(2)
	go Handshake(&wg)
	go GetTaskList(&wg)
	wg.Wait()

}
